package com.uniview.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;


/**
 * @Author lux
 * @date: 2019/11/20
 * @desc: 数据库配置
 */
@Configuration
@EnableTransactionManagement    // 一定要开启 支持@Transactional注解
@MapperScan(basePackages = "com.uniview.orm.daoX")	// Mybatis-Spring扫描Dao接口路径和扫描指定注解的类，类似于xml中配置MapperScannerConfigurer bean的属性
public class DataSourceConfiguration {
    /**
     * 创建数据源
     *
     * @return
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean(name = "dataSource")
    @Primary
    public DataSource createDataSource() {
        return new DruidDataSource();
    }

    /**
     * 创建事务管理器
     *
     * @param dataSource
     * @return
     */
    @Bean("transactionManager")
    public PlatformTransactionManager createTransactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
